Here's a somewhat useless error I'm getting in my Angular / TypeScript application. Until someone makes the error message better, what can we do about this? What are the most likely situations that cause this to happen?
Uncaught Error: Encountered undefined provider! Usually this means you have a circular dependencies (might be caused by using 'barrel' index.ts files.
at Object.syntaxError
at eval at Array.forEach (native) [<root>]
at CompileMetadataResolver._getProvidersMetadata
at CompileMetadataResolver.getNgModuleMetadata
at CompileMetadataResolver.getNgModuleSummary
at eval
...
It is very hard to tell from the error message which provider causes this issue. The way I managed to debug this is the following:
console.log('type', type); in order to see in which file is the undefined provider (You can also console log other relevant variables there).For me, I just restart the ng serve
One possibility is trying to declare a service and module in the same file, and declaring the module before the service:
import {Injectable, NgModule} from '@angular/core';
@NgModule({providers: [FooService]}) // WRONG: used before declared
export class FooModule {
}
@Injectable()
export class FooService {
}
You can fix this by declaring the service first, or you can use forwardRef like this:
import {forwardRef, Injectable, NgModule} from '@angular/core';
@NgModule({providers: [forwardRef(() => FooService)]})
export class FooModule {
}
@Injectable()
export class FooService {
}